package com.weilele.mvvm.utils.`object`

import android.graphics.Color
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import com.weilele.mvvm.base.MvvmDialog
import com.weilele.mvvm.base.helper.getActivityViewModel
import com.weilele.mvvm.base.helper.getViewModel
import com.weilele.mvvm.utils.activity.getScreenSize
import com.weilele.mvvm.utils.activity.dip
import com.weilele.mvvm.utils.safeGet
import com.weilele.mvvm.widget.BaseCardView

object EnvironmentHelper {
    private val listEnvironment =
        mutableListOf<Pair<String/*分类*/, MutableList<Pair<String/*备注*/, String/*url*/>>>>()

    /**
     * 设置一个新的环境集合
     */
    fun setEnvironment(environment: List<Pair<String/*分类*/, MutableList<Pair<String/*备注*/, String/*url*/>>>>) {
        clear()
        listEnvironment.addAll(environment)
    }

    /**
     * 添加一个环境
     */
    fun addEnvironment(environment: Pair<String/*分类*/, MutableList<Pair<String/*备注*/, String/*url*/>>>) {
        var isFind = false
        listEnvironment.forEach {
            if (it.first == environment.first) {
                isFind = true
                it.second.addAll(environment.second)
                return@forEach
            }
        }
        if (!isFind) {
            listEnvironment.add(environment)
        }
    }

    fun addSingleEnvironment(environment: Pair<String/*分类*/, Pair<String/*备注*/, String/*url*/>>) {
        var isFind = false
        listEnvironment.forEach {
            if (it.first == environment.first) {
                it.second.add(environment.second)
                isFind = true
                return@forEach
            }
        }
        if (!isFind) {
            addEnvironment(Pair(environment.first, mutableListOf(environment.second)))
        }
    }

    fun clear() {
        listEnvironment.clear()
    }

    fun getEnvironments() = listEnvironment

    fun open(
        activity: AppCompatActivity?, oldSelect: Pair<String, Pair<String, String>>?,
        selectListener: Function1<Pair<String, Pair<String, String>>?, Unit>?
    ) {
        activity ?: return
        //通过viewMode做中介，可以解决横竖屏切换问题
        activity.getViewModel<SelectListenerModel>().mSelectListener = selectListener
        EnvironmentDialog().apply {
            arguments = Bundle().also {
                it.putSerializable("datas", Pair("null", getEnvironments()))
                it.putSerializable("oldSelect", oldSelect)
            }
        }.safeShow(activity)
    }

    fun open(
        fragment: Fragment?, oldSelect: Pair<String, Pair<String, String>>?,
        selectListener: Function1<Pair<String, Pair<String, String>>?, Unit>?
    ) {
        fragment ?: return
        //通过viewMode做中介，可以解决横竖屏切换问题
        fragment.getViewModel<SelectListenerModel>().mSelectListener = selectListener
        EnvironmentDialog().apply {
            arguments = Bundle().also {
                it.putSerializable("datas", Pair("null", getEnvironments()))
                it.putSerializable("oldSelect", oldSelect)
            }
        }.show(fragment)
    }

    class SelectListenerModel : ViewModel() {
        var mSelectListener: Function1<Pair<String, Pair<String, String>>?, Unit>? = null
        override fun onCleared() {
            super.onCleared()
            mSelectListener = null
        }
    }

    class EnvironmentDialog : MvvmDialog() {
        private val mSelectListener by lazy { getActivityViewModel<SelectListenerModel>().mSelectListener }
        private var expandableListView: ExpandableListView? = null
        private var listEnvironment =
            mutableListOf<Pair<String/*分类*/, MutableList<Pair<String/*备注*/, String/*url*/>>>>()

        override fun getLayoutResOrView(inflater: LayoutInflater, parent: ViewGroup?): Any? {
            return BaseCardView(requireContext()).apply {
                radius = dip(8f)
                layoutParams = FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    requireActivity().getScreenSize().y * 3 / 4
                )
                elevation = dip(8f)
                addView(ExpandableListView(inflater.context).also {
                    it.layoutParams = FrameLayout.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT
                    )
                    expandableListView = it
                })
            }
        }

        override fun onRootViewLayoutParams(lp: FrameLayout.LayoutParams) {
            super.onRootViewLayoutParams(lp)
            lp.marginStart = dip(16)
            lp.marginEnd = lp.marginStart
        }

        override fun getClickView(): List<View?>? = null

        private fun createItem(): TextView {
            return TextView(context).apply {
                layoutParams = ViewGroup.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT
                )
                setPadding(dip(48), dip(12), dip(48), dip(12))
                setTextColor(Color.BLACK)
            }
        }

        override fun initUi(savedInstanceState: Bundle?) {
            arguments?.getSerializable("datas").safeGet<Pair<*, *>>()?.let {
                listEnvironment.addAll(it.second as Collection<Pair<String, MutableList<Pair<String, String>>>>)
            }
            expandableListView?.setOnChildClickListener { parent, v, groupPosition, childPosition, id ->
                val parentData = listEnvironment[groupPosition]
                mSelectListener?.invoke(Pair(parentData.first, parentData.second[childPosition]))
//                dismiss()
                true
            }
            val oldSelect = arguments?.getSerializable("oldSelect")
                ?.safeGet<Pair<String, Pair<String, String>>>()
            expandableListView?.setAdapter(object : BaseExpandableListAdapter() {
                override fun getGroup(groupPosition: Int): Any = groupPosition

                override fun isChildSelectable(groupPosition: Int, childPosition: Int): Boolean =
                    true

                override fun hasStableIds(): Boolean = true

                override fun getGroupView(
                    groupPosition: Int,
                    isExpanded: Boolean,
                    convertView: View?,
                    parent: ViewGroup?
                ): View {
                    val view = convertView.safeGet<TextView>() ?: createItem()
                    val text = listEnvironment[groupPosition].first
                    view.text = text
                    val textColor = if (text == oldSelect?.first) {
                        Color.GREEN
                    } else {
                        Color.BLACK
                    }
                    view.setTextColor(textColor)
                    return view
                }

                override fun getChildView(
                    groupPosition: Int,
                    childPosition: Int,
                    isLastChild: Boolean,
                    convertView: View?,
                    parent: ViewGroup?
                ): View {
                    val view = convertView.safeGet<TextView>() ?: createItem()
                    val parentData = listEnvironment[groupPosition]
                    val childData = parentData.second[childPosition]
                    childData.let {
                        view.text = "${it.first}\n${it.second}"
                    }
                    val textColor = if (parentData.first == oldSelect?.first
                        && childData.first == oldSelect.second.first
                        && childData.second == oldSelect.second.second
                    ) {
                        Color.GREEN
                    } else {
                        Color.BLACK
                    }
                    view.setTextColor(textColor)
                    return view
                }

                override fun getChildrenCount(groupPosition: Int): Int =
                    listEnvironment[groupPosition].second.count()

                override fun getChild(groupPosition: Int, childPosition: Int): Any = childPosition

                override fun getGroupId(groupPosition: Int): Long = groupPosition.toLong()


                override fun getChildId(groupPosition: Int, childPosition: Int): Long =
                    childPosition.toLong()

                override fun getGroupCount(): Int = listEnvironment.count()

            })
        }

        override fun initData() {
        }

        override fun onSingleClick(view: View) {
        }
    }
}